//    Copyright (C) 2013  <lugocreation@gmail.com>
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>
package org.jpgolay.wi.realestate;

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PrinterJob;
import java.beans.PropertyVetoException;
import java.math.BigDecimal;
import javax.swing.*;
import org.jpgolay.gui.iconBar.*;
import org.jpgolay.gui.progressBar.ProgressBar;
import org.jpgolay.gui.progressBar.SwingWorker;
import org.jpgolay.wi.agency.Agency;
import org.jpgolay.wi.agency.AgencyCRUD;
import org.jpgolay.wi.user.User;
import org.jpgolay.wi.util.BrowserControl;
import org.jpgolay.wi.util.WIDate;

// Referenced classes of package org.jpgolay.wi.realestate:
//            RealEstateCRUD, RealEstateGUI, RealEstate, RealEstatePrint
public class RealEstateController {

    public RealEstateController(String agencyId) {
        this.agencyId = "";
        userAdress = true;
        action = 0;
        law = false;
        open = false;
        this.agencyId = agencyId;
        initComponent();
        date = new WIDate();
    }

    private boolean initComponent() {
        if (crud == null) {
            crud = new RealEstateCRUD();
        }
        if (reGui == null || reGui.isClosed()) {
            reGui = new RealEstateGUI();
            reGui.getIconBar().addAnswerListener(new AnswerListener() {
                public void create(AnswerEvent e) {
                    actionCreate();
                }

                public void open(AnswerEvent e) {
                    actionOpen();
                }

                public void modify(AnswerEvent e) {
                    actionModify();
                }

                public void save(AnswerEvent e) {
                    actionSave();
                }

                public void remove(AnswerEvent e) {
                    actionRemove();
                }

                public void print(AnswerEvent e) {
                    actionPrint();
                }

                public void help(AnswerEvent e) {
                    actionHelp();
                }
            });
            reGui.setIconifiable(true);
            reGui.setResizable(false);
            reGui.setMaximizable(false);
            reGui.setClosable(true);
            reGui.setVisible(true);
            reGui.toFront();
            reGui.getHelpMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionHelp();
                }
            });
            reGui.getNewMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionCreate();
                }
            });
            reGui.getModifyMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionModify();
                }
            });
            reGui.getSaveMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionSave();
                }
            });
            reGui.getDeleteMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionRemove();
                }
            });
            reGui.getOpenMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    actionOpen();
                }
            });
            reGui.getPrintMI().addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    PrinterJob pj = PrinterJob.getPrinterJob();
                    if (pj.printDialog()) {
                        actionPrint();
                    }
                }
            });
            return true;
        }
        if (reGui.isIcon()) {
            try {
                reGui.setIcon(false);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        reGui.toFront();
        return false;
    }

    private void initMenu() {
        if (law) {
            reGui.getNewMI().setEnabled(true);
        }
        reGui.getHelpMI().setEnabled(true);
        reGui.getModifyMI().setEnabled(false);
        reGui.getOpenMI().setEnabled(true);
        reGui.getPrintMI().setEnabled(false);
        reGui.getDeleteMI().setEnabled(false);
        reGui.getSaveMI().setEnabled(false);
        if (law) {
            reGui.getIconBar().setEnabledCreate(true);
        }
        reGui.getIconBar().setEnabledHelp(true);
        reGui.getIconBar().setEnabledModify(false);
        reGui.getIconBar().setEnabledOpen(true);
        reGui.getIconBar().setEnabledPrint(false);
        reGui.getIconBar().setEnabledRemove(false);
        reGui.getIconBar().setEnabledSave(false);
    }

    private void openMenu() {
        if (law) {
            reGui.getNewMI().setEnabled(true);
        }
        reGui.getHelpMI().setEnabled(true);
        if (law) {
            reGui.getModifyMI().setEnabled(true);
        }
        reGui.getOpenMI().setEnabled(true);
        reGui.getPrintMI().setEnabled(true);
        reGui.getDeleteMI().setEnabled(false);
        reGui.getSaveMI().setEnabled(false);
        if (law) {
            reGui.getIconBar().setEnabledCreate(true);
        }
        reGui.getIconBar().setEnabledHelp(true);
        if (law) {
            reGui.getIconBar().setEnabledModify(true);
        }
        reGui.getIconBar().setEnabledOpen(true);
        reGui.getIconBar().setEnabledPrint(true);
        reGui.getIconBar().setEnabledRemove(false);
        reGui.getIconBar().setEnabledSave(false);
    }

    private void actionCreate() {
        action = 1;
        initContents();
        setEditable(true);
        reGui.getNewMI().setEnabled(false);
        reGui.getHelpMI().setEnabled(true);
        reGui.getModifyMI().setEnabled(false);
        reGui.getOpenMI().setEnabled(false);
        reGui.getPrintMI().setEnabled(true);
        reGui.getDeleteMI().setEnabled(false);
        reGui.getSaveMI().setEnabled(true);
        reGui.getIconBar().setEnabledCreate(false);
        reGui.getIconBar().setEnabledHelp(true);
        reGui.getIconBar().setEnabledModify(false);
        reGui.getIconBar().setEnabledOpen(false);
        reGui.getIconBar().setEnabledPrint(true);
        reGui.getIconBar().setEnabledRemove(false);
        reGui.getIconBar().setEnabledSave(true);
    }

    private void actionOpen() {
        setEditable(false);
        action = 0;
        open = true;
    }

    private void actionModify() {
        if (open) {
            setEditable(true);
            reGui.setEditableFicheIdFalse();
            action = 2;
            reGui.getNewMI().setEnabled(false);
            reGui.getHelpMI().setEnabled(true);
            reGui.getModifyMI().setEnabled(false);
            reGui.getOpenMI().setEnabled(false);
            reGui.getPrintMI().setEnabled(true);
            reGui.getDeleteMI().setEnabled(true);
            reGui.getSaveMI().setEnabled(true);
            reGui.getIconBar().setEnabledCreate(false);
            reGui.getIconBar().setEnabledHelp(true);
            reGui.getIconBar().setEnabledModify(false);
            reGui.getIconBar().setEnabledOpen(false);
            reGui.getIconBar().setEnabledPrint(true);
            reGui.getIconBar().setEnabledRemove(true);
            reGui.getIconBar().setEnabledSave(true);
        } else {
            JOptionPane.showMessageDialog(reGui, "Il n'y a aucune fiche \340 modifier !");
        }
    }

    private void actionSave() {
        if (action == 1 || action == 2) {
            setData();
        } else {
            JOptionPane.showMessageDialog(reGui, "Il n'y a aucune fiche \340 sauvegarder !");
        }
    }

    private void actionRemove() {
        if (action == 2) {
            remove();
        } else {
            JOptionPane.showMessageDialog(reGui, "Il n'y a aucune fiche \340 supprimer !\n(Pour supprimer une fiche entrer dans modifier)");
        }
    }

    private void actionPrint() {
        if (open) {
            print();
        } else {
            JOptionPane.showMessageDialog(reGui, "Il n'y a aucune fiche \340 imprimer !");
        }
    }

    private void actionHelp() {
        BrowserControl.displayURL("www.ifacile.com");
    }

    private void initContents() {
        reGui.initContents();
    }

    private void setEditable(boolean v) {
        reGui.setEditable(v);
    }

    public void setId(String id) {
        setEditable(false);
        action = 0;
        open = true;
        initContents();
        getData(id);
        reGui.toFront();
    }

    public void setInternalReference(String ref) {
        setEditable(false);
        action = 0;
        open = true;
        initContents();
        getDataByInternalRef(ref);
        reGui.toFront();
    }

    public IconBar getIb() {
        return reGui.getIconBar();
    }

    public JMenuItem getOpen() {
        return reGui.getOpen();
    }

    public RealEstateGUI getGUI() {
        return reGui;
    }

    public boolean isIb(IconBar iconBar) {
        return reGui.getIconBar().equals(iconBar);
    }

    public void iconified() {
    }

    public void unIconified() {
        if (reGui != null) {
            reGui.setVisible(true);
        }
    }

    public void maximizeFrame() {
        try {
            reGui.setMaximum(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    public boolean init() {
        boolean result = initComponent();
        if (result) {
            setLaw(usr);
        }
        return result;
    }

    private void remove() {
        int reponse = JOptionPane.showConfirmDialog(reGui, "Voulez-vous vraiment supprimer la fiche " + reGui.getId() + " ?", "Confirmation", 1, 2, null);
        switch (reponse) {
            default:
                break;

            case 0: // '\0'
                if (crud.remove()) {
                    JOptionPane.showMessageDialog(reGui, "La fiche num\351ro " + reGui.getId() + " est supprim\351e !");
                    initContents();
                    action = 0;
                    setEditable(false);
                } else {
                    JOptionPane.showMessageDialog(reGui, "Impossible de supprimer la fiche num\351ro " + reGui.getId() + " !" + "\nUn autre utilisateur l'a peut-\352tre modifi\351 entre temps.");
                }
                initMenu();
                break;

            case 1: // '\001'
                action = 0;
                setEditable(false);
                openMenu();
                break;

            case 2: // '\002'
                action = 0;
                setEditable(false);
                openMenu();
                break;

            case -1:
                action = 0;
                setEditable(false);
                openMenu();
                break;
        }
    }

    private void setData() {
        if (verifieRequis()) {
            SwingWorker worker = new SwingWorker() {
                public Object construct() {
                    startProgressBar();
                    boolean next = false;
                    switch (action) {
                        case 1: // '\001'
                            next = crud.create(agencyId);
                            if (next) {
                                reGui.setId(crud.getId());
                                realEstate = crud.getData();
                            }
                            break;

                        case 2: // '\002'
                            next = true;
                            break;
                    }
                    if (next) {
                        realEstate.setAddrLn1(reGui.getAdresse1());
                        realEstate.setAddrLn2(reGui.getAdresse2());
                        realEstate.setElevator(reGui.getAscenseur());
                        realEstate.setBalcony(reGui.getBalcon());
                        realEstate.setCategory(reGui.getCategorie());
                        realEstate.setDeposit(new BigDecimal(reGui.getCaution()));
                        realEstate.setCellar(reGui.getCave());
                        realEstate.setBedroom(reGui.getChambre());
                        realEstate.setCharge(new BigDecimal(reGui.getCharges()));
                        realEstate.setHeating(reGui.getChauffage());
                        realEstate.setFireplace(reGui.getCheminee());
                        realEstate.setKey(reGui.getClef());
                        realEstate.setCustomer(reGui.getClient());
                        realEstate.setZip(reGui.getCodePostal());
                        realEstate.setCounty(reGui.getCommune());
                        realEstate.setKitchen(reGui.getCuisine());
                        realEstate.setCreate(date.toDB(reGui.getDateCreation()));
                        realEstate.setAvailability(date.toDB(reGui.getDateDispo()));
                        if (action == 1) {
                            realEstate.setState("");
                            realEstate.setIdCustomer(new Integer(0));
                            realEstate.setNumConsultCC(new Integer(0));
                            realEstate.setNumConsultWeb(new Integer(0));
                            realEstate.setCountry("");
                            realEstate.setRef(new Integer(0));
                            realEstate.setPlot("");
                            realEstate.setVacation("");
                        }
                        realEstate.setLastUser(usr.getId().toString());
                        if (reGui.getDepartAccepte().equals("")) {
                            realEstate.setDeparture(null);
                        } else {
                            realEstate.setDeparture(date.toDB(reGui.getDepartAccepte()));
                        }
                        if (reGui.getDepartSouhaite().equals("")) {
                            realEstate.setDepartureCustomer(null);
                        } else {
                            realEstate.setDepartureCustomer(date.toDB(reGui.getDepartSouhaite()));
                        }
                        realEstate.setDescription(reGui.getDescriptif());
                        realEstate.setShower(reGui.getDouche());
                        realEstate.setFloor(reGui.getEtage());
                        realEstate.setCondition(reGui.getEtat());
                        realEstate.setAspect(reGui.getExposition());
                        realEstate.setAgencyFees(new BigDecimal(reGui.getFraisAgence()));
                        realEstate.setGarage(reGui.getGarage());
                        realEstate.setSort(reGui.getGenre());
                        realEstate.setHall(reGui.getHall());
                        realEstate.setGarden(reGui.getJardin());
                        realEstate.setLoggia(reGui.getLoggia());
                        realEstate.setBatch(reGui.getLot());
                        realEstate.setFurnished(reGui.getMeuble());
                        realEstate.setMezzanine(reGui.getMezzanine());
                        realEstate.setObservation(reGui.getObservation());
                        realEstate.setPrintObservation(reGui.getObservationImprimee());
                        realEstate.setOption(reGui.getOptions());
                        realEstate.setOptionFisc(reGui.getOptionFisc());
                        realEstate.setPanel(reGui.getPanneau());
                        realEstate.setParking(reGui.getParking());
                        realEstate.setPhoto1(reGui.getPhoto1());
                        realEstate.setPhoto2(reGui.getPhoto2());
                        realEstate.setPhoto3(reGui.getPhoto3());
                        realEstate.setPhoto4(reGui.getPhoto4());
                        realEstate.setPhoto5(reGui.getPhoto5());
                        realEstate.setPhoto6(reGui.getPhoto6());
                        realEstate.setPhoto7(reGui.getPhoto7());
                        realEstate.setPhoto8(reGui.getPhoto8());
                        realEstate.setPhoto9(reGui.getPhoto9());
                        realEstate.setPhoto10(reGui.getPhoto10());
                        realEstate.setPhotosValid(isPhotoValid(realEstate));
                        realEstate.setPool(reGui.getPiscine());
                        realEstate.setCupboard(reGui.getPlacard());
                        realEstate.setRent(new BigDecimal(reGui.getPrixLoyer()));
                        realEstate.setSale(new BigDecimal(reGui.getPrixVente()));
                        realEstate.setChargeDeposit(new BigDecimal(reGui.getProvisionCharge()));
                        realEstate.setArea(reGui.getQuartier());
                        if (reGui.getReserve().equals("")) {
                            realEstate.setReserve(null);
                        } else {
                            realEstate.setReserve(date.toDB(reGui.getReserve()));
                        }
                        realEstate.setResidance(reGui.getResidance());
                        realEstate.setRefInternal(reGui.getInternalId());
                        realEstate.setBathroom(reGui.getSalleBain());
                        realEstate.setSector(reGui.getSecteur());
                        realEstate.setLivingroom(reGui.getSejour());
                        realEstate.setStylefloor(reGui.getSol());
                        realEstate.setExitCustomer(reGui.getSortant());
                        realEstate.setStanding(reGui.getStanding());
                        realEstate.setSurfaceFloor(new Integer(reGui.getSurfaceHabitable()));
                        realEstate.setSurfaceGround(new Integer(reGui.getSurfaceTerrain()));
                        realEstate.setSKitchen(new Integer(reGui.getSurfaceCuisine()));
                        realEstate.setSBalcony(new Integer(reGui.getSurfaceBalcon()));
                        realEstate.setSGarage(new Integer(reGui.getSurfaceGarage()));
                        realEstate.setSLivingroom(new Integer(reGui.getSurfaceSejour()));
                        realEstate.setSHall(new Integer(reGui.getSurfaceHall()));
                        realEstate.setSRoofgarden(new Integer(reGui.getSurfaceTerrasse()));
                        realEstate.setSMezzanine(new Integer(reGui.getSurfaceMezzanine()));
                        realEstate.setSLoggia(new Integer(reGui.getSurfaceLoggia()));
                        realEstate.setSRoom(new Integer(reGui.getSurfaceChambre()));
                        realEstate.setSCellar(new Integer(reGui.getSurfaceCave()));
                        realEstate.setRoofgarden(reGui.getTerrasse());
                        realEstate.setType(reGui.getType());
                        realEstate.setLifeannuity(reGui.getViager());
                        realEstate.setWeb(reGui.getVisibilite());
                        realEstate.setRestroom(reGui.getWc());
                        realEstate.setBed(reGui.getLit());
                        realEstate.setTv(reGui.getTv());
                        realEstate.setArchive(reGui.getArchive());
                        realEstate.setAgencyId(new Integer(agencyId));
                        realEstate.setSCellarWine(new Integer(reGui.getSurfaceCellier()));
                        realEstate.setCellarWine(reGui.getCellier());
                        realEstate.setWalls(reGui.getMurs());
                        realEstate.setDuplex(reGui.getDuplex());
                        crud.setData(realEstate);
                        if (crud.modify()) {
                            stopProgressBar();
                            setEditable(false);
                            action = 0;
                            JOptionPane.showMessageDialog(reGui, "Op\351ration ex\351cut\351e avec succ\350s !");
                            openMenu();
                            return null;
                        } else {
                            stopProgressBar();
                            setEditable(false);
                            action = 0;
                            JOptionPane.showMessageDialog(reGui, "Op\351ration a \351chou\351e pour la fiche num\351ro " + reGui.getId() + " !" + "\nUn autre utilisateur l'a peut-\352tre modifi\351 entre temps.");
                            openMenu();
                            return null;
                        }
                    } else {
                        stopProgressBar();
                        setEditable(false);
                        action = 0;
                        JOptionPane.showMessageDialog(reGui, "L'op\351ration a \351chou\351 !\nV\351rifier que le num\350ro de Fiche n'est pas d\351j\340 utilis\351.");
                        openMenu();
                        return null;
                    }
                }
            };
            worker.start();
        }
    }

    private void getData(String id) {
        final String ID = id;
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                if (crud.findByPrimaryKey(ID)) {
                    realEstate = crud.getData();
                    reGui.setAdresse1(realEstate.getAddrLn1());
                    reGui.setAdresse2(realEstate.getAddrLn2());
                    reGui.setAscenseur(realEstate.getElevator());
                    reGui.setBalcon(realEstate.getBalcony());
                    reGui.setCategorie(realEstate.getCategory());
                    reGui.setCaution(realEstate.getDeposit().toString());
                    reGui.setCave(realEstate.getCellar());
                    reGui.setChambre(realEstate.getBedroom());
                    reGui.setCharges(realEstate.getCharge().toString());
                    reGui.setChauffage(realEstate.getHeating());
                    reGui.setCheminee(realEstate.getFireplace());
                    reGui.setClef(realEstate.getKey());
                    reGui.setClient(realEstate.getCustomer());
                    reGui.setCodePostal(realEstate.getZip());
                    reGui.setCommune(realEstate.getCounty());
                    reGui.setCuisine(realEstate.getKitchen());
                    reGui.setDateCreation(date.toPlain(realEstate.getCreate()));
                    reGui.setDateDispo(date.toPlain(realEstate.getAvailability()));
                    reGui.setDepartAccepte(date.toPlain(realEstate.getDeparture()));
                    reGui.setDepartSouhaite(date.toPlain(realEstate.getDepartureCustomer()));
                    reGui.setDescriptif(realEstate.getDescription());
                    reGui.setDouche(realEstate.getShower());
                    reGui.setEtage(realEstate.getFloor());
                    reGui.setEtat(realEstate.getCondition());
                    reGui.setExposition(realEstate.getAspect());
                    reGui.setId(realEstate.getId().toString());
                    reGui.setFraisAgence(realEstate.getAgencyFees().toString());
                    reGui.setGarage(realEstate.getGarage());
                    reGui.setGenre(realEstate.getSort());
                    reGui.setHall(realEstate.getHall());
                    reGui.setJardin(realEstate.getGarden());
                    reGui.setLoggia(realEstate.getLoggia());
                    reGui.setLot(realEstate.getBatch());
                    reGui.setMeuble(realEstate.getFurnished());
                    reGui.setMezzanine(realEstate.getMezzanine());
                    reGui.setObservation(realEstate.getObservation());
                    reGui.setObservationImprimee(realEstate.getPrintObservation());
                    reGui.setOptions(realEstate.getOption());
                    reGui.setOptionFisc(realEstate.getOptionFisc());
                    reGui.setPanneau(realEstate.getPanel());
                    reGui.setParking(realEstate.getParking());
                    reGui.setPhoto1(realEstate.getPhoto1());
                    reGui.setPhoto2(realEstate.getPhoto2());
                    reGui.setPhoto3(realEstate.getPhoto3());
                    reGui.setPhoto4(realEstate.getPhoto4());
                    reGui.setPhoto5(realEstate.getPhoto5());
                    reGui.setPhoto6(realEstate.getPhoto6());
                    reGui.setPhoto7(realEstate.getPhoto7());
                    reGui.setPhoto8(realEstate.getPhoto8());
                    reGui.setPhoto9(realEstate.getPhoto9());
                    reGui.setPhoto10(realEstate.getPhoto10());
                    reGui.setPiscine(realEstate.getPool());
                    reGui.setPlacard(realEstate.getCupboard());
                    reGui.setPrixLoyer(realEstate.getRent().toString());
                    reGui.setPrixVente(realEstate.getSale().toString());
                    reGui.setProvisionCharge(realEstate.getChargeDeposit().toString());
                    reGui.setQuartier(realEstate.getArea());
                    reGui.setReserve(date.toPlain(realEstate.getReserve()));
                    reGui.setResidance(realEstate.getResidance());
                    reGui.setInternalId(realEstate.getRefInternal());
                    reGui.setSalleBain(realEstate.getBathroom());
                    reGui.setSecteur(realEstate.getSector());
                    reGui.setSejour(realEstate.getLivingroom());
                    reGui.setSol(realEstate.getStylefloor());
                    reGui.setSortant(realEstate.getExitCustomer());
                    reGui.setStanding(realEstate.getStanding());
                    reGui.setSurfaceHabitable(realEstate.getSurfaceFloor().toString());
                    reGui.setSurfaceTerrain(realEstate.getSurfaceGround().toString());
                    reGui.setSurfaceCuisine(realEstate.getSKitchen().toString());
                    reGui.setSurfaceGarage(realEstate.getSGarage().toString());
                    reGui.setSurfaceBalcon(realEstate.getSBalcony().toString());
                    reGui.setSurfaceSejour(realEstate.getSLivingroom().toString());
                    reGui.setSurfaceHall(realEstate.getSHall().toString());
                    reGui.setSurfaceTerrasse(realEstate.getSRoofgarden().toString());
                    reGui.setSurfaceMezzanine(realEstate.getSMezzanine().toString());
                    reGui.setSurfaceLoggia(realEstate.getSLoggia().toString());
                    reGui.setSurfaceChambre(realEstate.getSRoom().toString());
                    reGui.setSurfaceCave(realEstate.getSCellar().toString());
                    reGui.setTerrasse(realEstate.getRoofgarden());
                    reGui.setType(realEstate.getType());
                    reGui.setViager(realEstate.getLifeannuity());
                    reGui.setVisibilite(realEstate.getWeb());
                    reGui.setWc(realEstate.getRestroom());
                    reGui.setLit(realEstate.getBed());
                    reGui.setTv(realEstate.getTv());
                    reGui.setArchive(realEstate.getArchive());
                    reGui.setSurfaceCellier(realEstate.getSCellarWine().toString());
                    reGui.setCellier(realEstate.getCellarWine());
                    reGui.setMurs(realEstate.getWalls());
                    reGui.setDuplex(realEstate.getDuplex());
                    stopProgressBar();
                    openMenu();
                    return null;
                } else {
                    stopProgressBar();
                    JOptionPane.showMessageDialog(reGui, "Impossible d'acc\351der \340 la fiche " + ID + " !");
                    openMenu();
                    return null;
                }
            }
        };
        worker.start();
    }

    private void getDataByInternalRef(String ref) {
        final String REF = ref;
        SwingWorker worker = new SwingWorker() {
            public Object construct() {
                startProgressBar();
                if (crud.findByInternalRefAndAgenceId(REF, agencyId)) {
                    realEstate = crud.getData();
                    reGui.setAdresse1(realEstate.getAddrLn1());
                    reGui.setAdresse2(realEstate.getAddrLn2());
                    reGui.setAscenseur(realEstate.getElevator());
                    reGui.setBalcon(realEstate.getBalcony());
                    reGui.setCategorie(realEstate.getCategory());
                    reGui.setCaution(realEstate.getDeposit().toString());
                    reGui.setCave(realEstate.getCellar());
                    reGui.setChambre(realEstate.getBedroom());
                    reGui.setCharges(realEstate.getCharge().toString());
                    reGui.setChauffage(realEstate.getHeating());
                    reGui.setCheminee(realEstate.getFireplace());
                    reGui.setClef(realEstate.getKey());
                    reGui.setClient(realEstate.getCustomer());
                    reGui.setCodePostal(realEstate.getZip());
                    reGui.setCommune(realEstate.getCounty());
                    reGui.setCuisine(realEstate.getKitchen());
                    reGui.setDateCreation(date.toPlain(realEstate.getCreate()));
                    reGui.setDateDispo(date.toPlain(realEstate.getAvailability()));
                    reGui.setDepartAccepte(date.toPlain(realEstate.getDeparture()));
                    reGui.setDepartSouhaite(date.toPlain(realEstate.getDepartureCustomer()));
                    reGui.setDescriptif(realEstate.getDescription());
                    reGui.setDouche(realEstate.getShower());
                    reGui.setEtage(realEstate.getFloor());
                    reGui.setEtat(realEstate.getCondition());
                    reGui.setExposition(realEstate.getAspect());
                    reGui.setId(realEstate.getId().toString());
                    reGui.setFraisAgence(realEstate.getAgencyFees().toString());
                    reGui.setGarage(realEstate.getGarage());
                    reGui.setGenre(realEstate.getSort());
                    reGui.setHall(realEstate.getHall());
                    reGui.setJardin(realEstate.getGarden());
                    reGui.setLoggia(realEstate.getLoggia());
                    reGui.setLot(realEstate.getBatch());
                    reGui.setMeuble(realEstate.getFurnished());
                    reGui.setMezzanine(realEstate.getMezzanine());
                    reGui.setObservation(realEstate.getObservation());
                    reGui.setObservationImprimee(realEstate.getPrintObservation());
                    reGui.setOptions(realEstate.getOption());
                    reGui.setOptionFisc(realEstate.getOptionFisc());
                    reGui.setPanneau(realEstate.getPanel());
                    reGui.setParking(realEstate.getParking());
                    reGui.setPhoto1(realEstate.getPhoto1());
                    reGui.setPhoto2(realEstate.getPhoto2());
                    reGui.setPhoto3(realEstate.getPhoto3());
                    reGui.setPhoto4(realEstate.getPhoto4());
                    reGui.setPhoto5(realEstate.getPhoto5());
                    reGui.setPhoto6(realEstate.getPhoto6());
                    reGui.setPhoto7(realEstate.getPhoto7());
                    reGui.setPhoto8(realEstate.getPhoto8());
                    reGui.setPhoto9(realEstate.getPhoto9());
                    reGui.setPhoto10(realEstate.getPhoto10());
                    reGui.setPiscine(realEstate.getPool());
                    reGui.setPlacard(realEstate.getCupboard());
                    reGui.setPrixLoyer(realEstate.getRent().toString());
                    reGui.setPrixVente(realEstate.getSale().toString());
                    reGui.setProvisionCharge(realEstate.getChargeDeposit().toString());
                    reGui.setQuartier(realEstate.getArea());
                    reGui.setReserve(date.toPlain(realEstate.getReserve()));
                    reGui.setResidance(realEstate.getResidance());
                    reGui.setInternalId(realEstate.getRefInternal());
                    reGui.setSalleBain(realEstate.getBathroom());
                    reGui.setSecteur(realEstate.getSector());
                    reGui.setSejour(realEstate.getLivingroom());
                    reGui.setSol(realEstate.getStylefloor());
                    reGui.setSortant(realEstate.getExitCustomer());
                    reGui.setStanding(realEstate.getStanding());
                    reGui.setSurfaceHabitable(realEstate.getSurfaceFloor().toString());
                    reGui.setSurfaceTerrain(realEstate.getSurfaceGround().toString());
                    reGui.setSurfaceCuisine(realEstate.getSKitchen().toString());
                    reGui.setSurfaceGarage(realEstate.getSGarage().toString());
                    reGui.setSurfaceBalcon(realEstate.getSBalcony().toString());
                    reGui.setSurfaceSejour(realEstate.getSLivingroom().toString());
                    reGui.setSurfaceHall(realEstate.getSHall().toString());
                    reGui.setSurfaceTerrasse(realEstate.getSRoofgarden().toString());
                    reGui.setSurfaceMezzanine(realEstate.getSMezzanine().toString());
                    reGui.setSurfaceLoggia(realEstate.getSLoggia().toString());
                    reGui.setSurfaceChambre(realEstate.getSRoom().toString());
                    reGui.setSurfaceCave(realEstate.getSCellar().toString());
                    reGui.setTerrasse(realEstate.getRoofgarden());
                    reGui.setType(realEstate.getType());
                    reGui.setViager(realEstate.getLifeannuity());
                    reGui.setVisibilite(realEstate.getWeb());
                    reGui.setWc(realEstate.getRestroom());
                    reGui.setLit(realEstate.getBed());
                    reGui.setTv(realEstate.getTv());
                    reGui.setArchive(realEstate.getArchive());
                    reGui.setSurfaceCellier(realEstate.getSCellarWine().toString());
                    reGui.setCellier(realEstate.getCellarWine());
                    reGui.setMurs(realEstate.getWalls());
                    reGui.setDuplex(realEstate.getDuplex());
                    stopProgressBar();
                    openMenu();
                    return null;
                } else {
                    stopProgressBar();
                    JOptionPane.showMessageDialog(reGui, "R\351f\351rence " + REF + " inconue !");
                    openMenu();
                    return null;
                }
            }
        };
        worker.start();
    }

    private boolean verifieRequis() {
        if (reGui.getCodePostal().length() > 5) {
            JOptionPane.showMessageDialog(reGui, "Code postal invalide !\n(maximum 5 chiffres)");
            return false;
        }
        if (reGui.getInternalId().length() > 20) {
            JOptionPane.showMessageDialog(reGui, "R\351ference trop longue !\n(maximum 20 caract\350res)");
            return false;
        }
        if (reGui.getDescriptif().length() > 250) {
            JOptionPane.showMessageDialog(reGui, "Observations Internet trop longue !\n(maximum 250 caract\350res)");
            return false;
        }
        if (reGui.getAdresse1().length() > 100) {
            JOptionPane.showMessageDialog(reGui, "Adresse premi\350re ligne trop longue !\n(maximum 100 caract\350res)");
            return false;
        }
        if (reGui.getAdresse2().length() > 100) {
            JOptionPane.showMessageDialog(reGui, "Adresse deuxi\350me ligne trop longue !\n(maximum 100 caract\350res)");
            return false;
        }
        if (reGui.getQuartier().length() > 20) {
            JOptionPane.showMessageDialog(reGui, "Quartier trop long !\n(maximum 20 caract\350res)");
            return false;
        }
        if (reGui.getLot().length() > 20) {
            JOptionPane.showMessageDialog(reGui, "Lot trop long !\n(maximum 20 caract\350res)");
            return false;
        }
        if (reGui.getCommune().length() > 50) {
            JOptionPane.showMessageDialog(reGui, "Commune trop longue !\n(maximum 50 caract\350res)");
            return false;
        }
        if (reGui.getSortant().length() > 250) {
            JOptionPane.showMessageDialog(reGui, "Sortant trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (reGui.getObservation().length() > 250) {
            JOptionPane.showMessageDialog(reGui, "Observations confidentiel trop longues !\n(maximum 250 caract\350res)");
            return false;
        }
        if (reGui.getObservationImprimee().length() > 250) {
            JOptionPane.showMessageDialog(reGui, "Observations imprim\351es trop longues !\n(maximum 250 caract\350res)");
            return false;
        }
        if (reGui.getResidance().length() > 100) {
            JOptionPane.showMessageDialog(reGui, "R\351sidance trop longue !\n(maximum 100 caract\350res)");
            return false;
        }
        if (reGui.getClient().length() > 250) {
            JOptionPane.showMessageDialog(reGui, "Client trop long !\n(maximum 250 caract\350res)");
            return false;
        }
        if (reGui.getPanneau().length() > 20) {
            JOptionPane.showMessageDialog(reGui, "Panneau trop long !\n(maximum 20 caract\350res)");
            return false;
        }
        if (!date.isValid(reGui.getDateCreation())) {
            JOptionPane.showMessageDialog(reGui, "WIDate de cr\351ation invalide !");
            return false;
        }
        if (!date.isValid(reGui.getDateDispo())) {
            JOptionPane.showMessageDialog(reGui, "WIDate de disponibilit\351 invalide !");
            return false;
        }
        if (reGui.getSurfaceHabitable().equals("")) {
            reGui.setSurfaceHabitable("0");
        }
        if (reGui.getSurfaceTerrain().equals("")) {
            reGui.setSurfaceTerrain("0");
        }
        if (reGui.getSurfaceCuisine().equals("")) {
            reGui.setSurfaceCuisine("0");
        }
        if (reGui.getSurfaceBalcon().equals("")) {
            reGui.setSurfaceBalcon("0");
        }
        if (reGui.getSurfaceGarage().equals("")) {
            reGui.setSurfaceGarage("0");
        }
        if (reGui.getSurfaceSejour().equals("")) {
            reGui.setSurfaceSejour("0");
        }
        if (reGui.getSurfaceHall().equals("")) {
            reGui.setSurfaceHall("0");
        }
        if (reGui.getSurfaceTerrasse().equals("")) {
            reGui.setSurfaceTerrasse("0");
        }
        if (reGui.getSurfaceMezzanine().equals("")) {
            reGui.setSurfaceMezzanine("0");
        }
        if (reGui.getSurfaceLoggia().equals("")) {
            reGui.setSurfaceLoggia("0");
        }
        if (reGui.getSurfaceChambre().equals("")) {
            reGui.setSurfaceChambre("0");
        }
        if (reGui.getSurfaceCave().equals("")) {
            reGui.setSurfaceCave("0");
        }
        if (reGui.getSurfaceCellier().equals("")) {
            reGui.setSurfaceCellier("0");
        }
        if (reGui.getPrixLoyer().equals("")) {
            reGui.setPrixLoyer("0");
        }
        if (reGui.getPrixVente().equals("")) {
            reGui.setPrixVente("0");
        }
        if (reGui.getCaution().equals("")) {
            reGui.setCaution("0");
        }
        if (reGui.getCharges().equals("")) {
            reGui.setCharges("0");
        }
        if (reGui.getFraisAgence().equals("")) {
            reGui.setFraisAgence("0");
        }
        if (reGui.getProvisionCharge().equals("")) {
            reGui.setProvisionCharge("0");
        }
        if (!date.isValid(reGui.getDepartAccepte())) {
            reGui.setDepartAccepte("");
        }
        if (!date.isValid(reGui.getDepartSouhaite())) {
            reGui.setDepartSouhaite("");
        }
        if (!date.isValid(reGui.getReserve())) {
            reGui.setReserve("");
        }
        try {
            new Integer(reGui.getSurfaceHabitable());
        } catch (NumberFormatException nfe) {
            JOptionPane.showMessageDialog(reGui, "Surface Habitable invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceTerrain());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Jardin invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceCuisine());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Cuisine invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceBalcon());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Balcon invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceGarage());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Garage invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceSejour());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Sejour invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceHall());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Hall invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceTerrasse());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Terrasse invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceMezzanine());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Mezzanine invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceLoggia());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Loggia invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceChambre());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Chambre invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceCave());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Cave invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getSurfaceCellier());
        } catch (NumberFormatException nfe1) {
            JOptionPane.showMessageDialog(reGui, "Surface Cellier invalide !\n(nombre entier uniquement)");
            return false;
        }
        try {
            new Integer(reGui.getCodePostal());
        } catch (NumberFormatException nfe2) {
            JOptionPane.showMessageDialog(reGui, "Code Postal invalide !\n(nombre entier de 5 chiffres maximum)");
            return false;
        }
        if (!reGui.getId().equals("")) {
            try {
                new Integer(reGui.getId());
            } catch (NumberFormatException nfe12) {
                JOptionPane.showMessageDialog(reGui, "Num\350ro de Fiche invalide !\n(nombre entier)");
                return false;
            }
        }
        try {
            new BigDecimal(reGui.getPrixLoyer());
        } catch (NumberFormatException nfe3) {
            JOptionPane.showMessageDialog(reGui, "Le montant Prix du Loyer est invalide !");
            return false;
        }
        try {
            new BigDecimal(reGui.getPrixVente());
        } catch (NumberFormatException nfe4) {
            JOptionPane.showMessageDialog(reGui, "Le montant Prix de Vente est invalide !");
            return false;
        }
        try {
            new BigDecimal(reGui.getCaution());
        } catch (NumberFormatException nfe5) {
            JOptionPane.showMessageDialog(reGui, "Le montant Caution est invalide !");
            return false;
        }
        try {
            new BigDecimal(reGui.getCharges());
        } catch (NumberFormatException nfe6) {
            JOptionPane.showMessageDialog(reGui, "Le montant Charges est invalide !");
            return false;
        }
        try {
            new BigDecimal(reGui.getFraisAgence());
        } catch (NumberFormatException nfe7) {
            JOptionPane.showMessageDialog(reGui, "Le montant Frais d'Agence est invalide !");
            return false;
        }
        try {
            new BigDecimal(reGui.getProvisionCharge());
            return true;
        } catch (NumberFormatException nfe) {
            JOptionPane.showMessageDialog(reGui, "Le montant Provision sur Charges est invalide !");
        }
        return false;
    }

    private String isPhotoValid(RealEstate data) {
        if (data.getPhoto1() == null && data.getPhoto2() == null && data.getPhoto3() == null && data.getPhoto4() == null && data.getPhoto5() == null && data.getPhoto6() == null && data.getPhoto7() == null && data.getPhoto8() == null && data.getPhoto9() == null && data.getPhoto10() == null) {
            return "non";
        } else {
            return "oui";
        }
    }

    private void startProgressBar() {
        if (pb == null) {
            pb = new ProgressBar(desktop, false);
            pb.setLocationRelativeTo(reGui);
            reGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        } else {
            reGui.setEnabled(false);
            pb.setVisible(true);
            pb.start();
        }
    }

    private void stopProgressBar() {
        if (!pb.isStop()) {
            pb.stop();
            pb.setVisible(false);
            reGui.setEnabled(true);
        }
    }

    private void print() {
        RealEstatePrint realestateprint;
        if (agencyAdress()) {
            realestateprint = new RealEstatePrint(realEstate, agency, false, null);
        }
    }

    private void setLaw(User usr) {
        String b = Long.toBinaryString(usr.getAccess().intValue());
        int position = b.length();
        if ((position -= 2) >= 0 && b.charAt(position) == '1') {
            law = true;
        } else {
            reGui.getNewMI().setEnabled(false);
            reGui.getModifyMI().setEnabled(false);
            reGui.getIconBar().setEnabledCreate(false);
            reGui.getIconBar().setEnabledModify(false);
        }
        initMenu();
    }

    public void setUser(User usr) {
        this.usr = usr;
        setLaw(usr);
    }

    public void setDefaultMainFrame(JFrame desktop) {
        this.desktop = desktop;
    }

    private boolean agencyAdress() {
        if (userAdress) {
            AgencyCRUD aCRUD = new AgencyCRUD();
            if (aCRUD.find(new Integer(agencyId))) {
                agency = aCRUD.getData();
                userAdress = false;
            } else {
                JOptionPane.showMessageDialog(reGui, "Le nom de l'utilisateur n'existe plus !");
            }
            return !userAdress;
        } else {
            return true;
        }
    }
    private RealEstate realEstate;
    private RealEstateGUI reGui;
    private RealEstateCRUD crud;
    private Agency agency;
    private ProgressBar pb;
    private WIDate date;
    private Dimension screen;
    private String agencyId;
    private User usr;
    private boolean userAdress;
    private int action;
    private final int CREATE = 1;
    private final int MODIFY = 2;
    private JFrame desktop;
    private boolean law;
    private boolean open;
}
